package com.tian.hello.ipc.client;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.tian.hello.R;
import com.tian.tianid.ILoginListener;
import com.tian.tianid.ILoginManager;
import com.tian.tianid.ipc.UserLoggedIn;

import java.util.List;

/**
 * 显示远程登录的用户消息
 */
public class ShowRemoteUserAc extends AppCompatActivity implements View.OnClickListener {

    private final String tag = ShowRemoteUserAc.class.getSimpleName();

    // 由AIDL文件生成的Java类
    private ILoginManager mLoginManager = null;
    private Button mAddBookBtn;

    // 标志当前与服务端连接状况的布尔值，false为未连接，true为连接中
    private boolean mBound = false;

    private final static String loginServicePck = "com.tian.tianid";
    private final static String loginServiceAction = "intent.action.bind_login_service";

    private final Handler uiHandler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
        mAddBookBtn = findViewById(R.id.btn);
        mAddBookBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        try {
            addBook(v);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void addBook(View view) throws RemoteException {
        //如果与服务端的连接处于未连接状态，则尝试连接
        if (!mBound) {
            attemptToBindService();
            return;
        }
        if (mLoginManager == null) return;

        mLoginManager.runLogin(new ILoginListener.Stub() {
            @Override
            public void onLoginSucess(UserLoggedIn user) {
                runOnUiThread(() -> Toast.makeText(getApplicationContext(), user.getUserId(), Toast.LENGTH_LONG).show());
            }

            @Override
            public void onLoginError(String error) {

            }
        });
    }

    /**
     * 尝试与服务端建立连接
     */
    private void attemptToBindService() {
        boolean isTargetAppRunning = isRunning(this, loginServicePck);
        log("isTargetAppRunning = " + isTargetAppRunning);
        if (isTargetAppRunning) {
            bindLoginService();
        } else {
            startServiceApp();
            uiHandler.postDelayed(this::bindLoginService,1000);
        }
    }

    /**
     * 判断某个app是否在运行
     *
     * @param context
     * @param pageName
     * @return
     */
    public boolean isRunning(Context context, String pageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> list = am.getRunningAppProcesses();
        if (list == null || list.isEmpty()) return false;
        for (ActivityManager.RunningAppProcessInfo appInfo : list) {
            if (appInfo.processName.equals(pageName)) {
                return true;
            }
        }
        return false;
    }

    private void bindLoginService() {
        Intent intent = new Intent();
        intent.setPackage(loginServicePck);
        intent.setAction(loginServiceAction);
        boolean isBindSuccess = bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        log("isBindSuccess = " + isBindSuccess);
    }

    private void startServiceApp() {
        PackageManager packageManager = getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(loginServicePck);
        startActivity(intent);
        log("startServiceApp ");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBound) {
            unbindService(mServiceConnection);
            mBound = false;
        }
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            log(Thread.currentThread().getName() + " service connected");
            mLoginManager = ILoginManager.Stub.asInterface(service);
            mBound = true;
            mAddBookBtn.setText("调用远程的登录方法");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            log("service disconnected");
            mBound = false;
        }
    };

    private void log(String msg) {
        Log.d(tag, msg);
    }

    private final IBinder.DeathRecipient deathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            log("binder died");
            if (mLoginManager != null) {
                mLoginManager.asBinder().unlinkToDeath(deathRecipient, 0);
                mLoginManager = null;
            }
            attemptToBindService();
        }
    };



}